<template>
  <div id="pro_adver">
    <div id="system_admin">
      <!--顶部搜索框内容开始-->
      <div class="role_seek">
        <el-select v-model="forms.status" placeholder="请选择广告状态">
          <el-option
            v-for="item in status"
            :key="item.staData"
            :label="item.staName"
            :value="item.staData"
          >
          </el-option>
        </el-select>
        <el-select v-model="forms.adType" placeholder="请选择广告类型">
          <el-option
            v-for="item in adTypes"
            :key="item.adData"
            :label="item.adName"
            :value="item.adData"
          >
          </el-option>
        </el-select>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="seek"
          v-power="'promote:advertisement:query'"
          >查找</el-button
        >
        <el-button size="mini" type="primary" icon="el-icon-edit" @click="add"
        v-power="'promote:advertisement:create'"
          >添加</el-button
        >
        <!--修改添加弹出框开始-->
        <el-dialog :title="title" :visible.sync="dialogFormVisible">
          <el-form
            :model="form"
            :rules="rules"
            ref="form"
            class="pop-up"
            status-icon
          >
            <el-form-item
              prop="title"
              label="广告标题"
              :label-width="formLabelWidth"
            >
              <el-input v-model="form.title" autocomplete="off"></el-input>
            </el-form-item>

            <el-form-item
              prop="imgUrl"
              label="广告图片"
              :label-width="formLabelWidth"
            >
              <el-upload
                class="avatar-uploader"
                action="http://192.168.1.99:8080/upload/admin"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
              >
                <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>

            <el-form-item
              prop="adType"
              label="广告类型"
              :label-width="formLabelWidth"
            >
              <el-select v-model="form.adType" placeholder="请选择广告类型">
                <el-option
                  v-for="item in adTypes"
                  :key="item.adData"
                  :label="item.adName"
                  :value="item.adData"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              prop="status"
              label="广告状态"
              :label-width="formLabelWidth"
            >
              <el-select v-model="form.status" placeholder="请选择广告状态">
                <el-option
                  v-for="item in status"
                  :key="item.staData"
                  :label="item.staName"
                  :value="item.staData"
                >
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item
              label="关联1"
              class="rolelds"
              :label-width="formLabelWidth"
            >
              <el-cascader
                :options="spulist"
                ref="dom"
                v-model="form.relevanceOne"
                :props="{ checkStrictly: true }"
                @change="relevanceoneMe"
              ></el-cascader>
            </el-form-item>

            <el-form-item
              label="关联2"
              class="rolelds"
              :label-width="formLabelWidth"
            >
              <el-select
                v-model="form.relevanceTwo"
                placeholder="请选择广告类型"
                @change="relevancetwoMe"
              >
                <el-option
                  v-for="item in group"
                  :key="item.groData"
                  :label="item.groName"
                  :value="item.groData"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="bool ? adduser('form') : compile('form')"
              >确 定</el-button
            >
          </div>
        </el-dialog>
        <!--修改添加弹出框结束-->
      </div>
      <!--顶部搜索框内容结束-->

      <!--底部列表内容部分-->
      <template>
        <el-table
          border
          :data="tableData"
          style="width: 100%"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column
            prop="id"
            label="广告ID"
            sortable
            align="center"
          ></el-table-column>
          <el-table-column
            prop="title"
            label="广告标题"
            align="center"
          ></el-table-column>
          <el-table-column label="广告类型" align="center">
            <template slot-scope="scope">
              <el-tag>
                {{ scope.row.adType | adTypeMe }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column label="广告状态" align="center">
            <template slot-scope="scope">
              <el-tag>
                {{ scope.row.status | statusMe }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="广告图片" align="center"
            ><template slot-scope="scope"
              ><img :src="scope.row.imgUrl" width="80px"/></template
          ></el-table-column>
          <el-table-column
            label="活动链接"
            align="center"
            prop="url"
          ></el-table-column>
          <el-table-column prop="address" label="操作" align="center">
            <template slot-scope="scope">
              <el-button
                class="button_redact"
                size="mini"
                @click="handleEdit(scope.row)"
                v-power="'promote:advertisement:update'"
                >编辑</el-button
              >
              <el-button
                class="button_remove"
                size="mini"
                type="danger"
                v-power="'promote:advertisement:delete'"
                @click="handleDelete(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!--底部列表内容部分结束-->

      <!--底部分页开始-->
      <div class="block">
        <Paging :forms="forms" :gain="gain"></Paging>
      </div>
      <!--底部分页结束-->
    </div>
  </div>
</template>

<script>
import Advertising from "@/api/promotion/Advertising";
import Paging from "../../components/Paging.vue"; //自定义组件

export default {
  data() {
    return {
      //弹出框
      formclone: [{}], //初始化克隆一遍表单
      spulist: [{}], //用于接收递归的数组
      tableData: [{}], //table里面的数据
      dialogFormVisible: false, //控制弹出框是否显示
      formLabelWidth: "120px", //弹出框宽度
      title: "创建", //弹出框标题
      bool: true, //布尔值 判断编辑还是修改 为true是创建 否则就是修改
      //分页
      forms: {
        adType: "", //类型
        status: "", //状态
        limit: 20, //limit
        total: 0, //分页
        pageNo: 1 //页码
      },

      //输入框数值
      form: {
        adType: "", //广告类型
        title: "", //广告标题
        url: "/pages/product/list?tid=", //广告地址
        imgUrl: "", //广告图片地址
        status: "", //广告状态
        color: "rgb(255 , 245, 238)", //图片颜色
        id: "", //广告ID
        relevanceOne: "", //关联1
        relevanceTwo: "" //关联2
      },
      //关联2的广告类型数据
      group: [{ groData: 1, groName: "团购信息" }],
      //状态选择框的数据
      status: [
        { staData: 0, staName: "冻结" },
        { staData: 1, staName: "激活" },
        { staData: null, staName: "全部" }
      ],
      //关联一以及分类的数据
      adTypes: [
        { adData: 1, adName: "轮播" },
        { adData: 2, adName: "分类精选" },
        { adData: 3, adName: "横幅" },
        { adData: 4, adName: "首页轮播下5按钮" },
        { adData: null, adName: "全部" }
      ],
      //弹出框验证
      rules: {
        title: [
          //广告标题
          { message: "广告标题不能为空", trigger: "change", required: true }
        ],
        imgUrl: [
          //广告图片地址
          { message: "广告图片不能为空", trigger: "change", required: true }
        ],
        adType: [
          //广告类型
          { message: "广告类型不能为空", trigger: "change", required: true }
        ],
        status: [
          //广告状态
          { message: "广告状态不能为空", trigger: "change", required: true }
        ]
      }
    };
  },
  components: {
    //注册分页组件
    Paging
  },
  created() {
    this.gain();
    Advertising.spu().then(res => {
      //spu树接口
      this.spulist = res.data.data;
      this.getTreeData(this.spulist);
      this.formclone = JSON.parse(JSON.stringify(this.form)); //将弹出框初始化状态克隆一份
    });
  },
  filters: {
    //状态过滤器
    statusMe(data) {
      if (data == 0) {
        return "冻结";
      } else {
        return "激活";
      }
    },
    //分类过滤器
    adTypeMe(data) {
      if (data == 1) {
        return "轮播";
      } else if (data == 2) {
        return "分类精选";
      } else if (data == 3) {
        return "横幅";
      } else if (data == 4) {
        return "首页轮播5按钮";
      } else {
        return "全部";
      }
    }
  },
  methods: {
    //当关联1有变动时触发
    relevanceoneMe(e) {
      if (e.length !== 3) {
        //是否选择了关联一
        this.Prosperity.Messages(" 此类广告只能关联三级类目", "error");
      }
      if (this.form.relevanceOne !== "") {
        //是否选择了关联二
        this.form.relevanceTwo = "";
      }
    },
    //当关联2有变动时触发
    relevancetwoMe() {
      if (this.form.relevanceTwo !== "") {
        this.form.relevanceOne = ""; //将关联1清空
      }
    },
    //获取列表数据内容
    gain() {
      var _this = this;
      Advertising.gain(_this.forms).then(res => {
        _this.tableData = res.data.data.items; //将接口列表内容赋值给列表数组
        _this.forms.total = res.data.data.total; //分页————条数
        _this.forms.limit = res.data.data.limit; //页码长度
        _this.forms.pageNo = res.data.data.pageNo; //页码
      });
    },
    //点击添加按钮触发
    add() {
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
      this.title = "创建"; //将标题改变
      this.form = JSON.parse(JSON.stringify(this.formclone)); //将form初始状态再次赋值给form表单
      this.bool = true; //bool为true触发添加接口
      this.dialogFormVisible = true; //显示弹出框
    },
    //添加接口
    adduser(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          if (
            this.form.relevanceOne.length === 3 ||
            this.form.relevanceTwo !== ""
          ) {
            if (this.form.relevanceOne) {
              //判断是否选择了类目 类目里有没有数据
              this.form.relevanceOne = this.$refs.dom.getCheckedNodes()[0].data.id; //获取数id并赋值
              this.form.url = this.form.url + this.form.relevanceOne; //拼接成活动链接
            } else if (this.form.relevanceTwo !== "") {
              //判断是否选择了关联2
              this.form.url = "/pages/groupshop/list";
            }
            var _this = this;
            Advertising.adduser(_this.form)
              .then(res => {
                if (res.data.errmsg == "成功") {
                  _this.gain(); //重新渲染页面
                  _this.Prosperity.Messages("添加成功", "success");
                  _this.dialogFormVisible = false;
                } else {
                  _this.Prosperity.Messages(res.data.errmsg, "error");
                }
              })
              .catch(err => {
                return err;
              });
          } else {
            //如果关联一额关联二都没选中就弹出提示
            this.Prosperity.Messages(" 此类广告只能关联三级类目", "error");
          }
        } else {
          return false;
        }
      });
    },
    //点击编辑按钮触发
    handleEdit(row) {
      //清空输入框下面的提示（输入错误）
      this.$nextTick(() => {
        if (this.$refs.form) {
          this.$refs.form.resetFields();
        }
      });
      this.form = { ...row };
      if (this.form.url) {
        //判断是否选择了类目 类目里有没有数据
        this.form.relevanceOne = "C_" + this.form.url.slice(24, 33); //将id拼接出来
      }
      this.bool = false; //改变bool 触发编辑接口
      this.title = "编辑"; //改变弹出框标题
      this.dialogFormVisible = true; //显示弹出框
    },

    //编辑接口
    compile(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          if (
            this.form.relevanceOne.length === 3 ||
            this.form.relevanceTwo !== ""
          ) {
            if (this.form.relevanceOne) {
              //判断是否选择了类目 类目里有没有数据
              this.form.relevanceOne = this.$refs.dom.getCheckedNodes()[0].data.id;
              this.form.url =
                "/pages/product/list?tid=" + this.form.relevanceOne;
            } else if (this.form.relevanceTwo !== "") {
              //是否选了关联二
              this.form.url = "/pages/groupshop/list";
            }
            var _this = this;
            Advertising.compile(_this.form).then(res => {
              if (res.data.errmsg == "成功") {
                _this.gain();
                //限制弹出框数量
                this.Prosperity.Messages("编辑成功", "success");
                this.dialogFormVisible = false;
              } else {
                this.Prosperity.Messages(res.data.errmsg, "error");
              }
            });
          } else {
            this.Prosperity.Messages(" 此类广告只能关联三级类目", "error");
          }
        } else {
          return false;
        }
      });
    },
    //搜索信息
    seek() {
      this.gain();
    },
    //点击删除按钮触发
    handleDelete(row) {
      this.form = { ...row };
      this.$confirm(
        "此操作将永久删除该广告---" + row.title + "---,是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          //确定删除的话 调用删除接口
          this.cancel();
        })
        .catch(() => {
          this.Prosperity.Messages("已取消删除");
        });
    },
    //删除内容接口
    cancel() {
      var _this = this;
      Advertising.cancel(_this.form)
        .then(res => {
          if (res.data.errmsg == "成功") {
            _this.gain(); //重新渲染
            this.Prosperity.Messages("删除成功", "success");
          } else {
            this.Prosperity.Messages(res.data.errmsg, "error");
          }
        })
        .catch(err => {
          return err;
        });
    },
    //递归
    getTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined;
        } else {
          this.getTreeData(data[i].children);
        }
      }
    },
    //上传图片
    handleAvatarSuccess(res) {
      this.form.imgUrl = res.url;
      this.$refs.form.clearValidate("imgUrl");
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    }
  }
};
</script>

<style scoped="scoped">
/*最大父盒子开始*/
#system_admin {
  padding: 20px;
}
/*最大父盒子结束*/

/*顶部index框开始*/
.el-input {
  margin-right: 5px;
}
.role_seek > .el-input {
  width: 200px !important;
  height: 40px !important;
}
.role_seek > .el-input > .el-input__inner {
  font-size: inherit;
  width: 50% !important;
  height: 100% !important;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
.role_input .el-input__suffix {
  left: 170px !important;
}
/*顶部index框结束*/

/*顶部按钮开始*/
.role_seek > .el-button--primary {
  line-height: 1px;
  font-size: 14px;
  border: 1px solid #409eff !important;
  background: #409eff !important;
  color: #fff;
  vertical-align: middle;
  padding: 12px 20px;
  margin-left: 5px;
}
/*顶部按钮结束*/

/*底部列表内容*/
.el-table {
  margin-top: 23px;
}
.cell {
  text-align: center;
  font-size: 12px;
  padding: 0px 10px;
}
.el-table__row > td {
  padding: 8px 0px;
}
.button_redact {
  background: #409eff !important;
  color: #fff !important;
  border: 1px solid #409eff;
}
/*编辑内容按钮*/
.button_redact:hover {
  background: #66b1ff !important;
  border: 1px solid #66b1ff;
}
.button_remove {
  background: #f56c6c !important;
  color: #fff !important;
  border: #f56c6c 1px solid;
}
.button_remove:hover {
  background: #f78989 !important;
  border: 1px solid #f78989;
}
.el-table--scrollable-x .el-table__body-wrapper {
  overflow-x: hidden;
}
/*底部列表内容*/

/*底部分页*/
.block {
  margin: 55px 0px;
}

/*底部分页结束*/

/*添加弹出框*/
.el-form-item img {
  width: 144px;
  height: 144px;
}
.el-form-item__label {
  text-align: left;
  margin-left: 50px;
  width: 85px !important;
}
.el-input__inner {
  text-indent: 5px;
}
.pop-up
  > .el-form-item
  > .el-form-item__content
  > .el-input
  > .el-input__inner {
  width: 268px !important;
  height: 38px;
  padding: 15px 0px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.pop-up > .el-form-item > .el-form-item__content > .el-form-item__error {
  left: 0px !important;
}

/*头像*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 143px;
  height: 143px;
  line-height: 143px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

/*添加弹出框结束*/
.el-select .el-input__inner {
  border: 1px solid #dcdfe6;
}
.el-select__caret {
  position: absolute;
  right: 58px !important;
}
.rolelds .el-input__suffix > i {
  position: absolute;
  right: 24px;
}
.el-select {
  margin-right: 5px;
}
</style>
